package z.z.mvc5;

import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import z.z.mvc5.utils.MyInterceptor;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableWebMvc
@ComponentScan("z.z.mvc5.controller") // 扫描注册类
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8") // 读取资源文件
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        // 添加 FastJson消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        fastConverter.setDefaultCharset(StandardCharsets.UTF_8);
        fastConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converters.add(fastConverter);
    }

    /**
     * 跨域配置
     * @param registry CorsRegistry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 跨域配置
        registry
                // 哪些url可以跨域
                .addMapping("/**")
                // 哪些HTTP header 可以跨域
                .allowedHeaders("*")
                // 哪些 请求方法可以跨域
                .allowedMethods("*")
                // 探测请求的有效期
                .maxAge(1800)
                // 哪些浏览器可以跨域
                .allowedOrigins("*");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry
                // 添加自定义拦截器
                .addInterceptor(new MyInterceptor())
                // 拦截哪些接口
                .addPathPatterns("/**");
        // 不拦截哪些接口
        // .excludePathPatterns("/hi");
    }

    /**
     * 文件上传配置
     * @return MultipartResolver
     */
    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    @Bean
    public SimpleClientHttpRequestFactory requestFactory () throws NoSuchAlgorithmException, KeyManagementException {

        // 创建一个全信任的 TrustManager，忽略所有证书验证
        TrustManager[] trustAllCertificates = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        // 不做任何检查
                    }
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        // 不做任何检查
                    }
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null; // 返回 null 允许所有证书
                    }
                }
        };
        // 创建一个 SSL 上下文并初始化
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCertificates, new java.security.SecureRandom());
        // 设置全局的 SSLContext
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(3 * 60 * 1000); // 3分钟
        requestFactory.setConnectTimeout(3 * 60 * 1000); // 3分钟
        return requestFactory;
    }

    /**
     * 注册RestTemplate组件
     * @return RestTemplate
     */
    @Bean
    public RestTemplate restTemplate(@Autowired SimpleClientHttpRequestFactory requestFactory){
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        // 配置StringHttpMessageConverter,使其默认的字符集为UTF-8
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) messageConverter).setDefaultCharset(StandardCharsets.UTF_8);
            }
        }
        return restTemplate;
    }
}
